"""
    源地址: -i https://pypi.tuna.tsinghua.edu.cn/simple
    1.安装必要的库
        PIL:
        pip install pillow -i https://mirrors.aliyun.com/pypi/simple
        reportlab-用于创建PDF文件:
        pip install reportlab -i https://pypi.tuna.tsinghua.edu.cn/simple
        PyPDF2-用于合并PDF文件:
        pip install PyPDF2 -i https://pypi.tuna.tsinghua.edu.cn/simple
"""


from PIL import Image
import os
from PyPDF2 import PdfMerger


def convert_images_to_pdf(file_path, num_photos_per_pdf):
    images = []
    output_dir = os.path.join(file_path, "pdf_files")
    os.makedirs(output_dir, exist_ok=True)

    # 获取目录下的所有照片文件
    for filename in os.listdir(file_path):
        if filename.endswith(".jpg") or filename.endswith(".png"):
            image_path = os.path.join(file_path, filename)
            # image = image.convert('RGB')
            image = Image.open(image_path)
            images.append(image)

    # 根据指定数量生成多个PDF文件
    num_photos = len(images)
    num_pdfs = num_photos // num_photos_per_pdf
    if num_photos % num_photos_per_pdf != 0:
        num_pdfs += 1

    for i in range(num_pdfs):
        start_index = i * num_photos_per_pdf
        end_index = min(start_index + num_photos_per_pdf, num_photos)
        pdf_images = images[start_index:end_index]

        pdf_path = os.path.join(output_dir, f"photos_{i+1}.pdf")
        if pdf_images:
            pdf_images[0].save(pdf_path, save_all=True, append_images=pdf_images[1:])
            print(f"生成PDF文件：{pdf_path}")

    print(f"共生成 {num_pdfs} 个PDF文件")

def merge_pdfs(file_path):
    output_dir = os.path.join(file_path, "merged_pdf")
    os.makedirs(output_dir, exist_ok=True)

    merger = PdfMerger()

    # 获取文件夹中的所有PDF文件
    pdf_files = [filename for filename in os.listdir(file_path) if filename.endswith(".pdf")]

    # 合并PDF文件
    for pdf_file in pdf_files:
        pdf_path = os.path.join(file_path, pdf_file)
        merger.append(pdf_path)

    # 保存合并后的PDF文件
    output_file = os.path.join(output_dir, "merged.pdf")
    merger.write(output_file)
    merger.close()

    print(f"合并后的PDF文件已保存为 {output_file}")

file_path = "./image_paths"
num_photos_per_pdf = 5  # 每个pdf页数

# 将照片转换为PDF
convert_images_to_pdf(file_path, num_photos_per_pdf)

# 合并生成的PDF文件
pdf_files_path = os.path.join(file_path, "pdf_files")
merge_pdfs(pdf_files_path)